package cn.jdemo.socket.zeroCopy.mmap;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SocketClient {
    public static void main(String[] args) throws IOException {
        mappedFile(Paths.get("D:\\zerocopy\\hello.txt"));
    }

    public static void mappedFile(Path filename) throws IOException {
        long start = System.currentTimeMillis();
        //1.打开通道
        SocketChannel socketChannel=SocketChannel.open();
        //2.连接指定ip和端口号
        socketChannel.connect (new InetSocketAddress("127.0.0.1",8880));
        //3.写出数据
        try (FileChannel fileChannel = FileChannel.open(filename)) {
            long size = fileChannel.size();//2147483647
            MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);
            socketChannel.write(mappedByteBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4.释放资源
        socketChannel.close();

        long end = System.currentTimeMillis();
        System.out.println("mappedFile执行耗时："+(end-start));
    }
}
